﻿using mediaControl.Event;
using mediaControl.Utils;
using mediaControl.Vo;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;

namespace mediaControl.ViewModels
{
    public class PlaySettingViewModel : BindableBase, IDialogAware
    {
        public string Title{get;set;}

        public event Action<IDialogResult> RequestClose;

        private double startWith;

        private double endWith; 

        private String volume="0";

        private int maxValue;

        private ProgramVo program;

        private ProgramItemVo programItemVo;

        //再次双加模式
        private String doubleMode="1";

        private string switchTime;
        //淡出时间
        private string switchOutTime;

        public DataTable DoubleModeTabe { get; set; }

        public DataTable SwitchTimeTabe { get; set; }

        /// <summary>
        /// 修改文件，保存文件信息
        /// </summary>
        public DelegateCommand ConfirmCommand { set; get; }

        public DelegateCommand JudgeCommand { set; get; }

        public double StartWith { get { return this.startWith; } set { this.startWith = value; RaisePropertyChanged();} }

        public string Volume { get { return this.volume; } set { this.volume = value; RaisePropertyChanged(); } }

        public ProgramVo Program { get { return program; } set { this.program = value; RaisePropertyChanged(); } }

        public ProgramItemVo ProgramItemVo { get => programItemVo; set => programItemVo = value; }
        public int MaxValue { get { return maxValue; } set { this.maxValue = value; RaisePropertyChanged(); } }

        public string DoubleMode { get { return doubleMode; } set { this.doubleMode = value; RaisePropertyChanged(); } }

        public string SwitchTime { get { return switchTime; } set { this.switchTime = value; RaisePropertyChanged(); } }

        public double EndWith { get { return endWith; } set { this.endWith = value; RaisePropertyChanged(); } }

        public string SwitchOutTime { get { return switchOutTime; } set { this.switchOutTime = value; RaisePropertyChanged(); } }

        //事件聚合器
        private readonly IEventAggregator eventAggregator;

        public PlaySettingViewModel(IEventAggregator eventAggregator)
        {
            ConfirmCommand = new DelegateCommand(confirm);
            JudgeCommand = new DelegateCommand(judge);
            this.eventAggregator = eventAggregator;

            DoubleModeTabe = new DataTable();
            DoubleModeTabe.Columns.Add("状态值");
            DoubleModeTabe.Columns.Add("状态显示");
            DoubleModeTabe.Rows.Add("1", "双击暂停");
            DoubleModeTabe.Rows.Add("2", "双击重头播放");

            SwitchTimeTabe = new DataTable();
            SwitchTimeTabe.Columns.Add("状态值");
            SwitchTimeTabe.Columns.Add("状态显示");
            SwitchTimeTabe.Rows.Add("0", "0S");
            SwitchTimeTabe.Rows.Add("1", "1S");
            SwitchTimeTabe.Rows.Add("2", "2S");
            SwitchTimeTabe.Rows.Add("3", "3S");
            SwitchTimeTabe.Rows.Add("4", "4S");
            SwitchTimeTabe.Rows.Add("5", "5S");
            SwitchTimeTabe.Rows.Add("6", "6S");
            SwitchTimeTabe.Rows.Add("7", "7S");
            SwitchTimeTabe.Rows.Add("8", "8S");
            SwitchTimeTabe.Rows.Add("9", "9S");
            SwitchTimeTabe.Rows.Add("10", "10S");
        }

        private void judge()
        {
            Regex regex = new Regex(@"^\d+$"); // 定义正则表达式，^表示开头，\d+表示至少一位数字，$表示结尾
            if (String.IsNullOrEmpty(Volume) && !regex.IsMatch(Volume))
            {
                MessageBox.Show("音量只能输入正整数");
                return;
            }
            if (Convert.ToInt32(Volume) > 100) {
                Volume = "100";
            }
        }

        private void confirm()
        {
            Regex regex = new Regex(@"^\d+$"); // 定义正则表达式，^表示开头，\d+表示至少一位数字，$表示结尾
            if (!String.IsNullOrEmpty(Volume) && !regex.IsMatch(Volume))
            {
                MessageBox.Show("音量只能输入正整数！");
                return;
            }
            if (StartWith >= EndWith) {
                MessageBox.Show("结束位置必须大于开始位置！");
                return;
            }
            String fileFullPath = program.FilePath + "\\" + program.Name + ".info"; // 指定要创建的文件路径及名
           
            try
            {
                if (!File.Exists(fileFullPath))
                {
                    MessageBox.Show("节目不存在！");
                    return;
                }
                string content = WriteFileUtil.readFile(fileFullPath);
                JObject programJson = JsonConvert.DeserializeObject<JObject>(content);
                ObservableCollection<ProgramItemVo> tempList = JsonConvert.DeserializeObject<ObservableCollection<ProgramItemVo>>((String)programJson.GetValue("programItems"));
                foreach (ProgramItemVo programItemVo in tempList)
                {
                    if (programItemVo.Id.Equals(ProgramItemVo.Id))
                    {
                        programItemVo.Volume = Volume;
                        programItemVo.StartWith = StartWith+"";
                        programItemVo.DoubleMode = DoubleMode;
                        programItemVo.SwitchTime = SwitchTime;
                        programItemVo.EndWith = EndWith + "";
                        programItemVo.SwitchOutTime = SwitchOutTime;
                    }
                }
                programJson["programItems"] = JsonConvert.SerializeObject(tempList);
                WriteFileUtil.writeFile(fileFullPath, JsonConvert.SerializeObject(programJson), "2");
                //保存节目信息
               
                //通知列表显示
                ProgramItemVo.Volume = Volume;
                ProgramItemVo.StartWith = StartWith + "";
                ProgramItemVo.DoubleMode = DoubleMode;
                ProgramItemVo.SwitchTime = SwitchTime;
                ProgramItemVo.EndWith = EndWith+"";
                ProgramItemVo.SwitchOutTime = SwitchOutTime;
                eventAggregator.GetEvent<ProgramItemEvent>().Publish(ProgramItemVo);
                IDialogParameters parameters = new DialogParameters();
                RequestClose?.Invoke(new Prism.Services.Dialogs.DialogResult(ButtonResult.OK, parameters));

            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法创建文件：{ex.Message}");
                return;
            }
        }

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            ProgramItemVo = parameters.GetValue<ProgramItemVo>("programItem");
            Program = parameters.GetValue<ProgramVo>("program");

            MaxValue = WriteFileUtil.getMusicTimes(ProgramItemVo.FilePath);
            if (!String.IsNullOrEmpty(ProgramItemVo.Volume))
            {
                Volume = ProgramItemVo.Volume;
            }
            if (!String.IsNullOrEmpty(ProgramItemVo.StartWith))
            {
                StartWith = Convert.ToDouble(ProgramItemVo.StartWith);
            }
            if (!String.IsNullOrEmpty(ProgramItemVo.EndWith))
            {
                EndWith = Convert.ToDouble(ProgramItemVo.EndWith);
            }
            else { 
                EndWith = MaxValue;
            }
            if (!String.IsNullOrEmpty(ProgramItemVo.DoubleMode)) { 
                DoubleMode = ProgramItemVo.DoubleMode;
            }
            if (!String.IsNullOrEmpty(ProgramItemVo.SwitchTime))
            {
                SwitchTime = ProgramItemVo.SwitchTime;
            }
            if (!String.IsNullOrEmpty(ProgramItemVo.SwitchOutTime))
            {
                SwitchOutTime = ProgramItemVo.SwitchOutTime;
            }
            this.Title = "播放设置";
        }
    }
}
